// Run our kitten generation script as soon as the document's DOM is ready.
var s1tokindle = {
    targetURL : "http://bbs.saraba1st.com/2b/read-htm-tid-937138.html",
    download_ : function(callback) {
	var req = new XMLHttpRequest();
	req.open("GET", this.targetURL, true);
	req.onload = function(evt) {
	    callback(evt.target.response)
	}
	req.onerror = function () {
	    document.body.innerHTML = "不能连接到S1服务器，大姨妈了";
	}
	req.send();
    },
    parse_ : function(callback, data) {
	var dummyNode = document.createElement("div");
	dummyNode.innerHTML = data;
	var posts = dummyNode.getElementsByClassName('f14');
	var result = []
	for (var i = 0 ; i != posts.length ; ++i) {
	    var postNode = this.closest_(posts[i], 'tbody');
	    if (!postNode) {
		continue;
	    }
	    var authorName = postNode.getElementsByClassName('readName')[0].textContent,
		tip        = postNode.getElementsByClassName('s2')[0].textContent +
			     postNode.getElementsByClassName('s2')[0].nextElementSibling.textContent,
		content    = postNode.getElementsByClassName('f14')[0].innerHTML;
	    result.push({
		'authorName': authorName,
		'tip'       : tip,
		'content'   : content
	    });
	}
	callback(result);
    },
    render_ : function(data) {
	var render = function(author, tip, content) {
	    return "<h2>" + authorName + "  " + tip + "</h2>" +
		   "<div>" + content + "</div>";
	}
	for (var i in data) {
	    document.body.innerHTML += render(data[i]);
	}
    },
    closest_ : function(node, tag) {
	while (node && node.tagName && node.tagName.toLowerCase() != tag.toLowerCase()) {
	    node = node.parentNode;
	}
	return node;
    },
    start : function () {
	this.download_(this.parse_.bind(this, function(result) {
	    var pre = document.createElement("pre");
	    document.body.appendChild(pre);
	    pre.innerHTML = JSON.stringify(result);
	}));
    }
};
document.addEventListener('DOMContentLoaded', function () {
    s1tokindle.start();
});
